<template>
  <div>
    <el-dialog
      title="项目列表"
      :visible.sync="show"
      :before-close="close"
      width="40%"
    >
      <div class="formBox">
        <div class="formHead">{{ title }}项目</div>
        <div class="formWhite">
          <div class="left"><span class="red">*</span>项目类型</div>
          <div class="right">
            <el-select
              v-model="submitForm.projectType"
              size="small"
              placeholder="请选择"
              @change="changeType"
              :disabled="editDisabled"
            >
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="formGray">
          <div class="left"><span class="red">*</span>项目名称</div>
          <div class="right">
            <div class="project-name-wrapper">
              <!-- <el-input
                v-model="submitForm.projectName"
                placeholder="请输入"
                size="small"
              ></el-input> -->
              <el-select
                ref="projectNameSelect"
                v-model="submitForm.projectName"
                v-if="submitForm.projectType !== '非住宅'"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="loading"
                :disabled="editDisabled"
                class="project-name-input"
              >
                <el-option
                  v-for="item in areaList"
                  :key="item.sectId"
                  :label="item.stNameFrst"
                  :value="item.stNameFrst"
                  @click.native="chooseArea(item)"
                >
                </el-option>
              </el-select>
              <el-input
                v-model="submitForm.projectName"
                v-if="submitForm.projectType === '非住宅'"
                placeholder="请输入"
                size="small"
                :disabled="editDisabled"
                class="project-name-input"
              ></el-input>
              <el-button
                size="small"
                type="primary"
                :disabled="editDisabled"
                @click="handleProjectNameButton"
                class="project-name-button"
                >以图查房</el-button
              >
            </div>
          </div>
        </div>
        <div class="formWhite area">
          <div class="left"><span class="red">*</span>所在地区</div>
          <div class="right">
            <el-select
              v-model="submitForm.projectLocation"
              size="small"
              placeholder="请选择区"
              class="areaLeft"
              :disabled="editDisabled"
              @change="onAreaChange"
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.addressId"
                :label="item.addressName"
                :value="item.addressName"
              ></el-option>
            </el-select>
            <el-select
              v-model="submitForm.projectStreet"
              size="small"
              placeholder="请选择街道"
              class="areaRight"
              :disabled="editDisabled"
              @change="onStreetChange"
              :key="`street-${streetOptions.length}-${submitForm.projectStreet}`"
            >
              <el-option
                v-for="item in streetOptions"
                :key="item.addressId"
                :label="item.addressName"
                :value="item.addressName"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="formGray">
          <div class="left"><span class="red">*</span>详细地址</div>
          <div class="right">
            <el-input
              v-model="submitForm.detailAddress"
              placeholder="请输入"
              size="small"
              :disabled="editDisabled"
            ></el-input>
          </div>
        </div>
        <div class="formWhite">
          <div class="left"><span class="red">*</span>所属白蚁防治公司</div>
          <div class="right">
            <el-select
              v-model="submitForm.controlId"
              size="small"
              placeholder="请选择"
              filterable
              :disabled="perDisabled || editDisabled"
            >
              <el-option
                v-for="item in companyList"
                :key="item.controlId"
                :value="item.controlId"
                :label="item.controlName"
              ></el-option>
            </el-select>
          </div>
        </div>
        <!-- <div class="formGray">
          <div class="left">经纬度</div>
          <div class="right">
            <el-input
              v-model="submitForm.latLong"
              placeholder="请输入"
              size="small"
              :disabled="editDisabled"
            ></el-input>
          </div>
        </div> -->
        <div class="formGray">
          <div class="left"><span class="red">*</span>小区物业公司</div>
          <div class="right">
            <el-input
              v-model="submitForm.propertyManagementCompany"
              placeholder="请输入"
              size="small"
              @input="onInput"
              :disabled="isPropertyCompanyDisabled"
            ></el-input>
          </div>
        </div>
        <div class="formWhite">
          <div class="left"><span class="red">*</span>运行状态</div>
          <div class="right">
            <el-select
              v-model="submitForm.runningState"
              size="small"
              placeholder="请选择"
              :disabled="editDisabled"
            >
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="enSure"
          size="small"
          v-if="!editDisabled"
          >确定</el-button
        >
        <el-button type="primary" plain @click="close" size="small"
          >取消</el-button
        >
      </span>
    </el-dialog>

    <!-- 以图查房抽屉 -->
    <ImageSearchDrawer
      :show="imageSearchDrawerVisible"
      @close="closeImageSearchDrawer"
      @selectSect="handleSelectSect"
    />
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  addProjectData, // 新增项目
  updateProjectData, // 项目编辑
  getURLWithToken, // 获取地图token
} from "@/api/manage/asset";

import {
  addressQuery, // 查询上海地址
  getControlCompanyData,
  getBaseInformation,
} from "@/api/manage/approval";
import ImageSearchDrawer from "./ImageSearchDrawer.vue";

export default {
  name: "addMsg",
  components: {
    ImageSearchDrawer,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    id: {
      default: "",
    },
    detailForm: {
      default: {},
    },
    title: {
      default: "",
    },
  },
  data() {
    return {
      submitForm: {
        projectName: "",
        projectType: "",
        projectLocation: "",
        projectStreet: "",
        detailAddress: "",
        controlId: "",
        // latLong: "",
        propertyManagementCompany: "",
        runningState: "",
      },
      areaOptions: [],
      streetOptions: [],
      areaList: [],
      typeList: [
        {
          value: "住宅",
          label: "住宅",
        },
        {
          value: "非住宅",
          label: "非住宅",
        },
      ],
      statusList: [
        {
          value: "运行中",
          label: "运行中",
        },
        {
          value: "停止",
          label: "停止",
        },
      ],
      companyList: [],
      loading: false,
      perDisabled: true,
      editDisabled: false,
      pendingProjectLocationValue: null,
      // 标记物业公司是否来自系统选择（item.cspName
      isPropertyCompanyFromSystem: false,
      // 由监听器维护的小区物业公司输入框禁用状态
      isPropertyCompanyDisabled: false,
      // 以图查房抽屉显示状态
      imageSearchDrawerVisible: false,
    };
  },
  created() {
    if (this.detailForm) {
      console.log(this.detailForm, "this.detailForm");

      this.submitForm = { ...this.detailForm };
      // 初始化时判断物业公司是否来自系统选择
      this.initPropertyCompanyStatus();
    }
    this.init();
    this.getAddress();
  },
  mounted() {
    if (["80", "81", "93"].includes(this.parentMsg.deptType)) {
      this.perDisabled = false;
    }
    if (this.title === "新增") {
      // this.submitForm.controlId = this.parentMsg.orgId;
      this.editDisabled = false;
    }
    if (this.title === "详情") {
      this.editDisabled = true;
    }
  },
  computed: {
    ...mapGetters(["parentMsg"]),
  },
  watch: {
    // 监听 detailForm 变化，当对话框打开并传入新数据时更新状态
    detailForm: {
      handler(newVal) {
        if (newVal && newVal.propertyManagementCompany) {
          // 初始化时判断物业公司是否来自系统选择
          this.initPropertyCompanyStatus();
        }
      },
      deep: true,
      immediate: false,
    },
    // 监听 show 变化，当对话框打开时初始化状态
    show(newVal) {
      if (newVal && this.detailForm) {
        // 对话框打开时，重新初始化状态
        this.$nextTick(() => {
          this.initPropertyCompanyStatus();
        });
      } else if (!newVal) {
        // 对话框关闭时，重置状态
        this.isPropertyCompanyFromSystem = false;
      }
    },
    // 监听项目类型变化
    "submitForm.projectType"(newVal) {
      // 当项目类型切换到"非住宅"时，允许编辑小区物业公司
      if (newVal === "非住宅") {
        this.isPropertyCompanyFromSystem = false;
      }
      // 如果切换到"住宅"，重置标记，等待用户重新选择项目
      else if (newVal === "住宅") {
        // 如果项目名称被清空，说明用户重新选择，重置标记
        if (!this.submitForm.projectName) {
          this.isPropertyCompanyFromSystem = false;
        }
        // 如果项目名称还有值，说明可能是编辑模式，需要根据实际情况判断
        // 这里不自动设置，保持当前状态或等待重新初始化
      }
      // 项目类型变化时，更新物业公司输入框禁用状态
      this.updatePropertyCompanyDisabled();
    },
    // 选项异步就绪后，若存在 pending 值，则补触发一次联动
    areaOptions(newList) {
      if (this.pendingProjectLocationValue) {
        const val = this.pendingProjectLocationValue;
        const obj =
          typeof val === "object"
            ? val
            : Array.isArray(newList)
              ? newList.find((i) => i.addressName === val)
              : null;
        if (obj) this.areaChange(obj);
        this.pendingProjectLocationValue = null;
      } else if (this.submitForm.projectLocation && newList.length > 0) {
        // 编辑模式下，如果已有区数据，需要加载对应的街道数据
        const selectedArea = newList.find(
          (item) => item.addressName === this.submitForm.projectLocation,
        );
        if (selectedArea) {
          this.areaChange(selectedArea);
        }
      }
    },
    // 监听物业公司内容变化
    "submitForm.propertyManagementCompany"() {
      this.updatePropertyCompanyDisabled();
    },
    // 监听是否来自系统选择标记变化
    isPropertyCompanyFromSystem() {
      this.updatePropertyCompanyDisabled();
    },
    // 监听整体编辑禁用状态变化
    editDisabled() {
      this.updatePropertyCompanyDisabled();
    },
    // 监听街道选项变化，确保回显正常
    streetOptions(newOptions) {
      if (newOptions && newOptions.length > 0) {
        // 如果当前有选中的街道值，确保它在新的选项中存在
        if (this.submitForm.projectStreet) {
          const exists = newOptions.some(
            (option) => option.addressName === this.submitForm.projectStreet,
          );
          if (!exists) {
            // 如果选中的值不在新选项中，清空它
            this.submitForm.projectStreet = "";
          }
        }
      }
    },
  },
  methods: {
    onInput(val) {
      this.$forceUpdate();
    },
    handleProjectNameButton() {
      console.log("以图查房按钮被点击");
      this.imageSearchDrawerVisible = true;
    },
    closeImageSearchDrawer() {
      this.imageSearchDrawerVisible = false;
    },
    // 关闭项目名称下拉框
    closeProjectNameDropdown() {
      this.$nextTick(() => {
        if (this.$refs.projectNameSelect) {
          // 使用 el-select 的方法来关闭下拉框
          const selectComponent = this.$refs.projectNameSelect;
          if (selectComponent && selectComponent.blur) {
            selectComponent.blur();
          }
          // 移除焦点，确保下拉框关闭
          const selectEl = selectComponent.$el;
          if (selectEl) {
            const inputEl = selectEl.querySelector(".el-input__inner");
            if (inputEl) {
              inputEl.blur();
            }
          }
        }
      });
    },
    // 处理从地图选中的小区
    handleSelectSect(sectName) {
      console.log("选中的小区名:", sectName);

      // 如果项目类型不是"非住宅"，需要触发搜索并显示下拉
      if (this.submitForm.projectType !== "非住宅") {
        // 先设置项目名称（这样搜索框会显示小区名）
        this.submitForm.projectName = sectName;

        // 触发远程搜索，获取匹配的列表
        this.remoteMethod(sectName);

        // 等待搜索完成后，自动选择匹配的项并触发 chooseArea
        this.$nextTick(() => {
          // 等待搜索接口返回数据后自动选择
          const checkAndSelect = () => {
            if (!this.loading && this.areaList.length > 0) {
              // 查找完全匹配的项
              const matchedItem = this.areaList.find(
                (item) => item.stNameFrst === sectName,
              );

              if (matchedItem) {
                // 找到完全匹配的项，自动调用 chooseArea 方法
                console.log("找到匹配的项，自动选择:", matchedItem);
                this.chooseArea(matchedItem);
                // 关闭下拉框
                this.closeProjectNameDropdown();
              } else if (this.areaList.length > 0) {
                // 如果没有完全匹配，选择第一个项
                console.log("未找到完全匹配，选择第一项:", this.areaList[0]);
                this.chooseArea(this.areaList[0]);
                // 关闭下拉框
                this.closeProjectNameDropdown();
              }
            } else if (this.loading) {
              // 如果还在加载中，继续等待
              setTimeout(checkAndSelect, 100);
            }
          };

          // 延迟检查，确保搜索完成
          setTimeout(checkAndSelect, 300);
        });
      } else {
        // 如果是"非住宅"，直接设置项目名称
        this.submitForm.projectName = sectName;
      }

      // 关闭抽屉
      this.imageSearchDrawerVisible = false;
    },
    onAreaChange(selectedValue) {
      // 根据选中的值找到对应的对象
      const selectedItem = this.areaOptions.find(
        (item) => item.addressName === selectedValue,
      );
      if (selectedItem) {
        // 先触发联动获取街道数据
        this.areaChange(selectedItem);

        // 延迟清空联动数据，确保联动完成后再清空
        this.$nextTick(() => {
          // 先清空街道
          this.$set(this.submitForm, "projectStreet", "");
          // 延迟清空物业公司，避免影响输入框状态
          setTimeout(() => {
            // 使用更温和的方式清空物业公司字段
            if (this.submitForm.propertyManagementCompany) {
              this.$set(this.submitForm, "propertyManagementCompany", "");
            }
            // 清空物业公司时，重置标记，允许手动编辑
            this.isPropertyCompanyFromSystem = false;
          }, 100);
        });
      } else {
        // 如果找不到对应的地区对象，记录日志并尝试根据值查找
        console.warn("未找到对应的地区对象:", selectedValue);
        // 如果地区选项为空，可能是数据还未加载完成，延迟处理
        if (!this.areaOptions || this.areaOptions.length === 0) {
          this.pendingProjectLocationValue = selectedValue;
        }
      }
    },
    onStreetChange(selectedValue) {
      // 强制更新组件，确保UI正确显示
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    init() {
      getControlCompanyData().then((res) => {
        if (res.errorCode === "000000") {
          this.companyList = res.data;
          if (this.title === "新增" && this.companyList.length > 0) {
            this.submitForm.controlId = this.companyList[0].controlId;
            this.submitForm.controlName = this.companyList[0].controlName;
          }
        }
      });
    },
    getAddress() {
      // 查询上海地址
      addressQuery({}).then((res) => {
        console.log(res, "res");
        if (res.errorCode === "000000") {
          this.areaOptions = res.data;
        }
      });
    },
    areaChange(val) {
      console.log(val, "areaChange0-0-0-0-0-0-");
      if (val) {
        // 查询街道地址
        addressQuery({ faId: val.addressId }).then((res) => {
          console.log(res, "res");
          if (res.errorCode === "000000") {
            this.streetOptions = res.data || [];
            // 强制更新组件，确保街道选项正确显示
            this.$nextTick(() => {
              this.$forceUpdate();
            });
          }
        });
      }
    },
    remoteMethod(query) {
      console.log(query, "query");
      if (!query) {
        this.areaList = [];
        return;
      }
      this.loading = true;
      const data = {
        pageNumber: "1",
        pageSize: "20",
        sectId: "",
        stNameFrst: query,
      };
      getBaseInformation(data)
        .then((res) => {
          if (res.errorCode === "000000") {
            this.areaList = res.data || [];
            console.log("搜索到的列表:", this.areaList);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    chooseArea(item) {
      console.log(item, "0-0-0-0-0-0-0-0-0-0-0-0-");
      if (item) {
        this.submitForm.projectLocation = item.hpbName;
        this.submitForm.projectStreet = item.strName;
        const hasPropertyCompany =
          item.cspName !== null &&
          item.cspName !== undefined &&
          String(item.cspName).trim() !== "";

        this.submitForm.propertyManagementCompany = hasPropertyCompany
          ? item.cspName
          : "";
        this.submitForm.detailAddress = item.stAddrFrst;

        // 根据 item.cspName 是否为空来标记物业公司是否来自系统选择
        // 如果 cspName 不为空，说明是系统选择的，需要禁用输入框
        // 如果 cspName 为空，说明可以手动编辑
        this.isPropertyCompanyFromSystem = hasPropertyCompany;

        // 当通过搜索框选择项目后，需要根据选中的地区加载对应的街道数据
        // 确保在地区数据加载完成后，能够正确加载街道数据
        this.$nextTick(() => {
          if (this.areaOptions && this.areaOptions.length > 0) {
            const selectedArea = this.areaOptions.find(
              (area) => area.addressName === item.hpbName,
            );
            if (selectedArea) {
              this.areaChange(selectedArea);
            }
          } else {
            // 如果地区数据还未加载，等待加载完成后再处理
            this.pendingProjectLocationValue = item.hpbName;
          }
        });
      }
    },
    changeType(val) {
      // 当项目类型从"住宅"切换到"非住宅"时，允许编辑小区物业公司
      if (val === "非住宅") {
        this.isPropertyCompanyFromSystem = false;
      }
      // 如果切换到"住宅"，且之前是通过搜索框选择的（有物业公司值），需要重新判断
      // 但这里不自动设置，因为需要等待用户重新选择项目
    },
    enSure() {
      console.log("确定按钮", this.submitForm);

      if (!this.submitForm.projectType) {
        this.$modal.msgWarning("项目类型不能为空！");
      } else if (!this.submitForm.projectName) {
        this.$modal.msgWarning("项目名称不能为空！");
      } else if (!this.submitForm.projectLocation) {
        this.$modal.msgWarning("请选择区！");
      } else if (!this.submitForm.projectStreet) {
        this.$modal.msgWarning("请选择街道！");
      } else if (!this.submitForm.detailAddress) {
        this.$modal.msgWarning("详细地址不能为空！");
      } else if (!this.submitForm.controlId) {
        this.$modal.msgWarning("请选择所属白蚁防治公司！");
      } else if (!this.submitForm.runningState) {
        this.$modal.msgWarning("请选择运行状态！");
      } else {
        if (this.submitForm.projectId) {
          // 编辑
          updateProjectData(this.submitForm).then((res) => {
            console.log(res, "22222222");
            if (res.errorCode == "000000") {
              this.$modal.msgSuccess("编辑项目成功");
              this.$emit("closeMsg", true);
            }
          });
        } else {
          addProjectData(this.submitForm).then((res) => {
            console.log(res, "000000000");
            if (res.errorCode == "000000") {
              this.$modal.msgSuccess("新增项目成功");
              this.$emit("closeMsg", true);
            }
          });
        }
      }
    },
    close() {
      console.log(1111);
      this.$emit("closeMsg");
    },
    // 使用监听器维护物业公司输入框禁用状态
    updatePropertyCompanyDisabled() {
      // 详情模式下始终禁用
      if (this.editDisabled) {
        this.isPropertyCompanyDisabled = true;
        return;
      }
      // 项目类型为“非住宅”时，小区物业公司始终可以编辑
      if (this.submitForm.projectType === "非住宅") {
        this.isPropertyCompanyDisabled = false;
        return;
      }
      // 判断当前是否有物业公司值
      const hasPropertyCompany =
        this.submitForm.propertyManagementCompany &&
        String(this.submitForm.propertyManagementCompany).trim() !== "";
      // 项目类型为“住宅”时：
      // - 如果选择的项目返回的 cspName 为空（在 chooseArea 中会把 isPropertyCompanyFromSystem 置为 false），允许编辑
      // - 如果 cspName 有值，且标记为来自系统选择，则禁用
      if (this.submitForm.projectType === "住宅") {
        this.isPropertyCompanyDisabled =
          this.isPropertyCompanyFromSystem && hasPropertyCompany;
        return;
      }
      // 其他类型按是否来自系统选择控制
      this.isPropertyCompanyDisabled =
        this.isPropertyCompanyFromSystem && hasPropertyCompany;
    },
    // 初始化物业公司状态：判断是否来自系统选择
    initPropertyCompanyStatus() {
      // 如果 detailForm 中有 cspName 字段且不为空，说明是系统选择的
      if (this.detailForm && this.detailForm.cspName) {
        this.isPropertyCompanyFromSystem = true;
      }
      // 如果有 isPropertyCompanyFromSystem 标记字段，直接使用
      else if (
        this.detailForm &&
        this.detailForm.isPropertyCompanyFromSystem !== undefined
      ) {
        this.isPropertyCompanyFromSystem =
          this.detailForm.isPropertyCompanyFromSystem;
      }
      // 如果 propertyManagementCompany 有值，且项目类型是"住宅"（住宅项目通过搜索框选择）
      // 那么很可能是系统选择的，设置为 true
      else if (
        this.detailForm &&
        this.detailForm.propertyManagementCompany &&
        this.detailForm.projectType === "住宅"
      ) {
        // 住宅项目且物业公司有值，很可能是系统选择的
        this.isPropertyCompanyFromSystem = true;
      }
      // 其他情况默认允许编辑
      else {
        this.isPropertyCompanyFromSystem = false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.headerTable {
  background: #5d6d7f;
  height: 48px;
  line-height: 48px;
  text-align: center;
  width: 100%;
  color: #fff;
  font-weight: Bold;
  font-size: 14px;
  font-family:
    Helvetica Neue,
    Helvetica,
    PingFang SC,
    Hiragino Sans GB,
    Microsoft YaHei,
    Arial,
    sans-serif;
  border: 1px solid #e3e3e3;
  border-bottom: 0;
}

.formBox {
  .left {
    display: inline-block;
    height: 44px;
    line-height: 44px;
    width: 140px;
    padding-right: 15px;
    border-left: 1px solid #e4e4dc;
    border-right: 1px solid #e4e4dc;
    font-family: MicrosoftYaHei;
    font-size: 12px;
    color: #303133;
    text-align: right;
    vertical-align: top;
  }
  .right {
    display: inline-block;
    width: calc(100% - 140px);
    height: 44px;
    border-right: 1px solid #e4e4dc;
    padding: 6px 15px;
    .el-select {
      width: 100% !important;
    }
    .el-input {
      width: 100% !important;
    }
    // 项目名称行的特殊样式
    .project-name-wrapper {
      display: flex;
      align-items: center;
      gap: 10px;
      height: 100%;
      .project-name-input {
        flex: 1;
        .el-input__inner,
        .el-input {
          width: 100% !important;
        }
      }
      .project-name-button {
        flex-shrink: 0;
      }
    }
  }
  .formHead {
    width: 100%;
    height: 44px;
    background-color: #73879c;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-family: MicrosoftYaHei, MicrosoftYaHei;
    font-weight: bold;
    font-size: 12px;
    color: #ffffff;
  }
  .formWhite {
    width: 100%;
    height: 44px;
    background-color: #fff;
    border-bottom: 1px solid #e4e4dc;
  }
  .area {
    .areaLeft {
      width: 40% !important;
      margin-right: 10px;
    }
    .areaRight {
      width: calc(60% - 10px) !important;
    }
  }
  .formGray {
    width: 100%;
    height: 44px;
    background-color: #eef0f2;
    border-bottom: 1px solid #e4e4dc;
  }
}
.red {
  color: red;
  margin-right: 2px;
  vertical-align: top;
}
::v-deep .el-dialog__header {
  border-bottom: 1px solid #e9e9ec;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #e9e9ec;
}
</style>
